package com.apartmentManage.controller;

import com.apartmentManage.entity.Apartment;
import com.apartmentManage.entity.ApartmentTutor;
import com.apartmentManage.service.ApartmentService;
import com.apartmentManage.until.Renter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/apartment")
public class ApartmentController {

    @Autowired
    private ApartmentService service;

    @GetMapping("/getAll")
    public String getAll(Model model){
        Renter renter = new Renter(service.getAll() != null ? true : false, service.getAll());
        model.addAttribute(renter);
        return "pages/apartment/List";
    }

    @GetMapping("/getByRequirement")
    public String getByRequirement(Apartment apartment, Model model){
        List<Apartment> result =
                service.getByRequirement(apartment);
        Renter renter = new Renter(result != null ? true : false, result);
        model.addAttribute("renter",renter);
        return "pages/apartment/List";
    }

    @GetMapping("/getByNo/{apartmentNo}")
    public String getByNo(@PathVariable("apartmentNo") Integer apartmentNo,Model model){
        Apartment result = service.getByNo(apartmentNo);
        new Renter(result!=null ? true : false,result);
        model.addAttribute("result",result);
        return "pages/apartment/update";
    }

    @PostMapping("/save")
    public  String save(Apartment apartment){
        if (apartment.getApartmentNo()==null || apartment.getApartmentNo()==0
        || apartment.getStatus()==null || apartment.getStatus()==""){
            return "redirect:/apartment/addView";
        }
        boolean flag = service.add(apartment);
        new Renter(flag);
        if (flag)
            return "redirect:/apartment/getAll";
        return "redirect:/apartment/addView";

    }

    @GetMapping("/addView")
    public String addView(){
        return "pages/apartment/add";
    }

    @GetMapping("/delete/{apartmentNo}")
    public  String Delete(@PathVariable("apartmentNo") Integer apartmentNo){
        if (apartmentNo==0 || apartmentNo==null){
            return "redirect:/apartment/getAll";
        }
        boolean falg = service.delete(apartmentNo);
        new Renter(falg);
        return "redirect:/apartment/getAll";
    }

    @PostMapping("/update")
    public  String update(Apartment apartment){
        boolean flag = service.update(apartment);
        new Renter(flag);
        if (flag)
           return "redirect:/apartment/getAll";
        return "redirect:/apartment/getByNo/"+apartment.getApartmentNo();
    }
}
